package org.jeecg.modules.wangyue.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wangyue.constant.*;
import org.jeecg.modules.wangyue.entity.*;
import org.jeecg.modules.wangyue.mapper.*;
import org.jeecg.modules.wangyue.model.req.ReqVipModel;
import org.jeecg.modules.wangyue.service.IConfigurationService;
import org.jeecg.modules.wangyue.service.IPerformanceFlowService;
import org.jeecg.modules.wangyue.service.IUserBasicService;
import org.jeecg.modules.wangyue.utils.CommonUtil;
import org.jeecg.modules.wangyue.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户基本信息表
 * @Author: jeecg-boot
 * @Date:   2023-06-30
 * @Version: V1.0
 */
@Service
public class UserBasicServiceImpl extends ServiceImpl<UserBasicMapper, UserBasic> implements IUserBasicService {

    @Autowired
    private UserBasicMapper userBasicMapper;
    @Autowired
    private UserRoleInfoMapper userRoleInfoMapper;
    @Autowired
    private DistributorUserMapper distributorUserMapper;
    @Autowired
    private DistributorJsMapper distributorJsMapper;
    @Autowired
    private IConfigurationService configurationService;
    @Autowired
    private IPerformanceFlowService performanceFlowService;
    @Autowired
    private ConfigurationMapper configurationMapper;
    @Autowired
    private CapitalFlowMapper capitalFlowMapper;
    @Autowired
    private CompanyFlowMapper companyFlowMapper;
    @Autowired
    private IndentVipMapper indentVipMapper;


    @Override
    public boolean isAccountRegistered(String account) {
        QueryWrapper<UserBasic> userBasicQueryWrapper = new QueryWrapper<>();
        userBasicQueryWrapper.eq("account", account);
        userBasicQueryWrapper.eq("is_block", IsBlockConstant.no);
        userBasicQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        List<UserBasic> userBasics = userBasicMapper.selectList(userBasicQueryWrapper);
        if(oConvertUtils.isNotEmpty(userBasics) && userBasics.size() > 0){
            return true; //注册过
        }
        return false; //没注册过
    }

    @Override
    public boolean isPromoterExist(String promotionCode) {
        QueryWrapper<UserBasic> userBasicQueryWrapper = new QueryWrapper<>();
        userBasicQueryWrapper.eq("promotion_code", promotionCode);
        userBasicQueryWrapper.eq("is_block", IsBlockConstant.no);
        userBasicQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        List<UserBasic> userBasics = userBasicMapper.selectList(userBasicQueryWrapper);
        if(oConvertUtils.isNotEmpty(userBasics) && userBasics.size() > 0){
            return true; //存在
        }
        return false; //不存在
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean userSignUp(String account, String password, String isPromotion, String promotionCode, String roleType) {
        try {
            String uuid = CommonUtil.uuid32();
            //随机生成8位数推广码，判断是否唯一，不唯一则再生成一次
            boolean isOnly = false;
            String userPromotionCode = "";
            while(!isOnly){
                userPromotionCode = CommonUtil.promotionCode();
                QueryWrapper<UserBasic> userBasicQueryWrapper = new QueryWrapper<>();
                userBasicQueryWrapper.eq("promotion_code", userPromotionCode);
                userBasicQueryWrapper.eq("is_block", IsBlockConstant.no);
                userBasicQueryWrapper.eq("del_flag", DelFlagConstant.normal);
                List<UserBasic> userBasics =  userBasicMapper.selectList(userBasicQueryWrapper);
                if(!(oConvertUtils.isNotEmpty(userBasics) && userBasics.size() > 0)){ //说明唯一
                    isOnly = true;
                }
            }

            /*1.用户基础表tb_user_basic新增一条数据*/
            UserBasic userBasic = new UserBasic();
            userBasic.setId(uuid);
            userBasic.setAccount(account);
            userBasic.setPassword(SecureUtil.md5(password));
            userBasic.setRegisterPhone(account);
            userBasic.setPromotionCode(userPromotionCode);
            userBasicMapper.insert(userBasic);

            /*2.获取配置参数*/
            QueryWrapper<Configuration> configurationQueryWrapper = new QueryWrapper<>();
            configurationQueryWrapper.eq("param_type", ConfigParamConstant.basicParamType);
            configurationQueryWrapper.eq("del_flag", DelFlagConstant.normal);
            List<Configuration> configurationList = configurationService.list(configurationQueryWrapper);
            double firstRegisterAmount = 0.0; //第一次注册平台业绩金额(元)
            double inviteFriendsAmount = 0.0; //邀请好友送N元推广金额(元)
            for(Configuration configuration : configurationList){
                if(ConfigParamConstant.firstRegisterAmount.equals(configuration.getId())){
                    firstRegisterAmount = Double.valueOf(configuration.getParamValue());
                }else if(ConfigParamConstant.inviteFriendsAmount.equals(configuration.getId())){
                    inviteFriendsAmount = Double.valueOf(configuration.getParamValue());
                }
            }

            /*3.用户角色表tb_user_role_info新增两条数据*/
            UserRoleInfo yhRoleInfo = new UserRoleInfo();
            yhRoleInfo.setUserId(uuid);
            yhRoleInfo.setUserType(RoleConstant.yonghu);
            yhRoleInfo.setUserName("用户WY_" + account);
            yhRoleInfo.setPhone(account);
            yhRoleInfo.setHeadPicUrl(CommonConstant.defaultHeadUrl);
            if(IsPromotionConstant.yes.equals(isPromotion)){ //有推广
                if(RoleConstant.yonghu.equals(roleType)){
                    yhRoleInfo.setTotalAmount(new BigDecimal(firstRegisterAmount));
                }
            }else{//没有推广
                yhRoleInfo.setTotalAmount(new BigDecimal(firstRegisterAmount));
            }
            userRoleInfoMapper.insert(yhRoleInfo);
            UserRoleInfo jsRoleInfo = new UserRoleInfo();
            jsRoleInfo.setUserId(uuid);
            jsRoleInfo.setUserType(RoleConstant.jishi);
            jsRoleInfo.setUserName("技师WY_" + account);
            jsRoleInfo.setPhone(account);
            jsRoleInfo.setHeadPicUrl(CommonConstant.defaultHeadUrl);
            if(IsPromotionConstant.yes.equals(isPromotion)){
                if(RoleConstant.jishi.equals(roleType)){
                    jsRoleInfo.setTotalAmount(new BigDecimal(firstRegisterAmount));
                }
            }
            userRoleInfoMapper.insert(jsRoleInfo);

            /*4.是否推广*/
            //有推广
            if(IsPromotionConstant.yes.equals(isPromotion)){
                QueryWrapper<UserBasic> pUserBasicQueryWrapper = new QueryWrapper<>();
                pUserBasicQueryWrapper.eq("promotion_code", promotionCode);
                pUserBasicQueryWrapper.eq("is_block", IsBlockConstant.no);
                pUserBasicQueryWrapper.eq("del_flag", DelFlagConstant.normal);
                UserBasic promoterUserBasic = userBasicMapper.selectOne(pUserBasicQueryWrapper);
                //如果有推广人，则在对应的角色分销表(表tb_distributor_user 或 表tb_distributor_js)新增一条数据
                if(RoleConstant.yonghu.equals(roleType)){
                    DistributorUser distributorUser = new DistributorUser();
                    distributorUser.setPromotionUserId(promoterUserBasic.getId());
                    distributorUser.setPromotionUserType(RoleConstant.yonghu);
                    distributorUser.setPromotedUserId(uuid);
                    distributorUser.setPromotedUserType(RoleConstant.yonghu);
                    distributorUserMapper.insert(distributorUser);
                }else if(RoleConstant.jishi.equals(roleType)){
                    DistributorJs distributorJs = new DistributorJs();
                    distributorJs.setPromotionUserId(promoterUserBasic.getId());
                    distributorJs.setPromotionUserType(RoleConstant.jishi);
                    distributorJs.setPromotedUserId(uuid);
                    distributorJs.setPromotedUserType(RoleConstant.jishi);
                    distributorJsMapper.insert(distributorJs);
                }
                //如果有推广人，业绩流水表新增一条“注册业绩”和新增一条“推广邀请业绩”
                //注册业绩
                List<PerformanceFlow> performanceFlowList = new ArrayList<>();
                PerformanceFlow registerPerformance = new PerformanceFlow();
                registerPerformance.setUserId(uuid);
                registerPerformance.setAccount(account);
                registerPerformance.setUserType(roleType);
                registerPerformance.setChangeType(PerformanceFlowConstant.registeredType);
                registerPerformance.setChangeName(PerformanceFlowConstant.registeredName);
                registerPerformance.setCommissionChange(new BigDecimal(firstRegisterAmount));
                registerPerformance.setUpOrDown(PerformanceFlowConstant.amountUp);
                registerPerformance.setIsIntoBalance(PerformanceFlowConstant.notTransferred);
                performanceFlowList.add(registerPerformance);
                //推广邀请业绩
                PerformanceFlow promotionInvitation = new PerformanceFlow();
                promotionInvitation.setUserId(promoterUserBasic.getId());
                promotionInvitation.setAccount(promoterUserBasic.getAccount());
                promotionInvitation.setUserType(roleType);
                promotionInvitation.setChangeType(PerformanceFlowConstant.promotionInvitationType);
                promotionInvitation.setChangeName(PerformanceFlowConstant.promotionInvitationName);
                promotionInvitation.setCommissionChange(new BigDecimal(inviteFriendsAmount));
                promotionInvitation.setUpOrDown(PerformanceFlowConstant.amountUp);
                promotionInvitation.setPromotedUserId(uuid);
                promotionInvitation.setPromotedUserType(roleType);
                promotionInvitation.setIsIntoBalance(PerformanceFlowConstant.notTransferred);
                performanceFlowList.add(promotionInvitation);
                performanceFlowService.saveBatch(performanceFlowList);
                //将“推广金额”放入推广人的总金额中(行上锁)
                UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(promoterUserBasic.getId(), roleType);
                UpdateWrapper<UserRoleInfo> userRoleInfoUpdateWrapper = new UpdateWrapper<>();
                userRoleInfoUpdateWrapper.eq("id", userRoleInfo.getId());
                userRoleInfoUpdateWrapper.set("total_amount", userRoleInfo.getTotalAmount().add(new BigDecimal(inviteFriendsAmount)));
                int userRoleInfoNum = userRoleInfoMapper.update(null, userRoleInfoUpdateWrapper);
                if(userRoleInfoNum < 1){
                    throw new RuntimeException();
                }
            }else{//没有推广
                //如果没有推广人，则新增一条用户的“注册业绩”
                //注册业绩
                PerformanceFlow registerPerformance = new PerformanceFlow();
                registerPerformance.setUserId(uuid);
                registerPerformance.setAccount(account);
                registerPerformance.setUserType(RoleConstant.yonghu);
                registerPerformance.setChangeType(PerformanceFlowConstant.registeredType);
                registerPerformance.setChangeName(PerformanceFlowConstant.registeredName);
                registerPerformance.setCommissionChange(new BigDecimal(firstRegisterAmount));
                registerPerformance.setUpOrDown(PerformanceFlowConstant.amountUp);
                registerPerformance.setIsIntoBalance(PerformanceFlowConstant.notTransferred);
                performanceFlowService.save(registerPerformance);
            }

            return true;
        }catch (Exception e){
//            e.printStackTrace();
            throw new RuntimeException("注册失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Result<?> openVip(String orderNo) {
        //通过订单号查询出userId、userType、vipId数据
        QueryWrapper<IndentVip> indentVipQueryWrapper = new QueryWrapper<>();
        indentVipQueryWrapper.eq("order_no", orderNo);
        indentVipQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        IndentVip indentVip = indentVipMapper.selectOne(indentVipQueryWrapper);
        if(oConvertUtils.isEmpty(indentVip)){
            return Result.error("找不到订单号信息");
        }

        //先判断是否开通vip，如果没开通，可继续执行VIP开通操作
        String userId = indentVip.getUserId();
        String userType = indentVip.getUserType();
        String vipId = indentVip.getVipId();
        QueryWrapper<UserBasic> userBasicQueryWrapper = new QueryWrapper<>();
        userBasicQueryWrapper.eq("id", userId);
        userBasicQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        //查询账号
        UserBasic userBasic = userBasicMapper.selectOne(userBasicQueryWrapper);
        if(oConvertUtils.isNotEmpty(userBasic) && IsVipConstant.no.equals(userBasic.getIsVip())){ //未开通VIP会员
            //1.资金流水、公司流水
            //查询用户余额(行上锁)
            UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(userId, userType);
            //查询开通vip的信息
            QueryWrapper<Configuration> configurationQueryWrapper = new QueryWrapper<>();
            configurationQueryWrapper.eq("id", vipId);
            configurationQueryWrapper.eq("del_flag", DelFlagConstant.normal);
            Configuration configuration = configurationMapper.selectOne(configurationQueryWrapper);
            BigDecimal amount = new BigDecimal(configuration.getParamValue());
            //资金流水-充值
            CapitalFlow capitalFlow = new CapitalFlow();
            capitalFlow.setUserId(userRoleInfo.getUserId());
            capitalFlow.setAccount(userBasic.getAccount());
            capitalFlow.setUserType(userRoleInfo.getUserType());
            capitalFlow.setChangeType(CapitalFlowTypeConstant.recharge); //0-充值
            capitalFlow.setChangeName(CapitalFlowTypeConstant.rechargeName + "(-开通VIP)"); //充值
            capitalFlow.setBeforeChangeAmount(userRoleInfo.getBalance());
            capitalFlow.setChangeAmount(amount);
            capitalFlow.setAfterChangeAmount(userRoleInfo.getBalance().add(amount));
            capitalFlow.setUpOrDown(CapitalFlowTypeConstant.money_up);
            int capitalFlowNum = capitalFlowMapper.insert(capitalFlow);
            if(capitalFlowNum < 1){
                throw new RuntimeException("开通VIP-失败(1)");
            }
            //资金流水-消费
            CapitalFlow capitalFlow2 = new CapitalFlow();
            capitalFlow2.setUserId(userRoleInfo.getUserId());
            capitalFlow2.setAccount(userBasic.getAccount());
            capitalFlow2.setUserType(userRoleInfo.getUserType());
            capitalFlow2.setChangeType(CapitalFlowTypeConstant.consumption); //1-消费
            capitalFlow2.setChangeName(CapitalFlowTypeConstant.consumptionName + "(-开通VIP)"); //消费
            capitalFlow2.setBeforeChangeAmount(userRoleInfo.getBalance().add(amount));
            capitalFlow2.setChangeAmount(amount.negate());
            capitalFlow2.setAfterChangeAmount(userRoleInfo.getBalance());
            capitalFlow2.setUpOrDown(CapitalFlowTypeConstant.money_down);
            int capitalFlowNum2 = capitalFlowMapper.insert(capitalFlow2);
            if(capitalFlowNum2 < 1){
                throw new RuntimeException("开通VIP-失败(2)");
            }
            //公司流水-平台收入
            CompanyFlow companyFlow = new CompanyFlow();
            companyFlow.setChangeType(CompanyFlowConstant.revenue); //1-平台收入
            companyFlow.setChangeName(CompanyFlowConstant.revenueName); //平台收入
            companyFlow.setChangeAmount(amount);
            companyFlow.setUpOrDown(CompanyFlowConstant.money_up);
            companyFlow.setUserId(userRoleInfo.getUserId());
            companyFlow.setUserType(userRoleInfo.getUserType());
            int companyFlowNum = companyFlowMapper.insert(companyFlow);
            if(companyFlowNum < 1){
                throw new RuntimeException("开通VIP-失败(3)");
            }

            UpdateWrapper<UserBasic> userBasicUpdateWrapper = new UpdateWrapper<>();
            userBasicUpdateWrapper.eq("id", userId);
            userBasicUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
            userBasicUpdateWrapper.set("is_vip", IsVipConstant.yes);
            long aDay = 1000L * 60 * 60 * 24;
            if(ConfigParamConstant.vipMonth.equals(vipId)){ //月卡
                userBasicUpdateWrapper.set("vip_date", DateUtil.getTimeStrToMillis("yyyy-MM-dd", aDay * ConfigParamConstant.vipMonthToDays));
            }else if(ConfigParamConstant.vipQuarter.equals(vipId)){ //季卡
                userBasicUpdateWrapper.set("vip_date", DateUtil.getTimeStrToMillis("yyyy-MM-dd", aDay * ConfigParamConstant.vipQuarterToDays));
            }else if(ConfigParamConstant.vipYear.equals(vipId)){ //年卡
                userBasicUpdateWrapper.set("vip_date", DateUtil.getTimeStrToMillis("yyyy-MM-dd", aDay * ConfigParamConstant.vipYearToDays));
            }else if(ConfigParamConstant.vipLife.equals(vipId)){ //终身卡
                userBasicUpdateWrapper.set("vip_date", ConfigParamConstant.vipLifeToDate);
            }else {
                return Result.error("vip会员信息出错！");
            }
            if(userBasicMapper.update(null, userBasicUpdateWrapper) > 0){
                return Result.OK("vip会员开通成功！");
            }
        }
//        return Result.error("vip会员开通失败！");
        return Result.error(9999, "vip会员开通失败-该用户已开通会员");
    }


//    public static void main(String[] args) {
//        long aDay = 1000L * 60 * 60 * 24;
//        System.out.println(DateUtil.getTimeStrToMillis("yyyy-MM-dd", aDay * ConfigParamConstant.vipMonthToDays));
//        System.out.println(DateUtil.getTimeStrToMillis("yyyy-MM-dd", aDay * ConfigParamConstant.vipQuarterToDays));
//        System.out.println(DateUtil.getTimeStrToMillis("yyyy-MM-dd", aDay * ConfigParamConstant.vipYearToDays));
//        System.out.println(ConfigParamConstant.vipLifeToDate);
//    }

}
